#ifndef _CONNECTION_HPP_20120407
#define _CONNECTION_HPP_20120407

#include "base.hpp"
#include "sock_addr.hpp"
#include "listbuffer.hpp"

#include "iprocessor.hpp"
#include "idatagram_factory.hpp"
#include "idatagram.hpp"

using namespace buffer;
using namespace datagram;

class FixedSizeAllocator;

namespace tcp
{
	class ConnManager;
	
	class Connection
	{
		public :
			Connection(FixedSizeAllocator & alloc);
			Connection(FixedSizeAllocator & alloc, SockAddr & addr);
			~Connection();

			int close();

			/// for connector
			int connect();
			
			/// for acceptor
			int listen();

			Connection * accept();

			void write(IDatagram * datagram);

			/// read event
			void read();

			/// write event
			void write();

			/// error event
			void error();

			// get/set
			int fd() const { return _fd; }
			bool is_good() const { return (-1 != _fd); }

			const SockAddr & sock_addr() const { return _sock_addr; }

			uint32_t  conn_id() const { return _conn_id; };
			void      conn_id(uint32_t id) { _conn_id = id; }

			bool listen_only() const { return _listen_only; }
			void listen_only(bool lo) { _listen_only = lo; }
		public :
			int                        _fd;

			SockAddr                   _sock_addr;
			ListBuffer                 _wr_buff;
			ListBuffer                 _rd_buff;

			IProcessor  *              _processor;
			IDatagramFactory *         _factory;

			ConnManager *              _conn_mgr;
		private :
			bool                       _listen_only;
			uint32_t                   _conn_id;

		private :
			void setup_socket();
	};
};

#endif

